from flask import Blueprint, request, jsonify
from models import RequirementModel, SolutionModel
from services import PromptTemplateService
import logging

logger = logging.getLogger(__name__)

def create_routes(db):
    """创建路由蓝图"""
    api = Blueprint('api', __name__, url_prefix='/api')
    
    # 初始化模型
    requirement_model = RequirementModel(db)
    solution_model = SolutionModel(db)
    
    # ==================== 需求表单相关接口 ====================
    
    @api.route('/requirements', methods=['POST'])
    def create_requirement():
        """创建需求表单"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    'success': False,
                    'message': '请求数据不能为空'
                }), 400
            
            success, message, requirement = requirement_model.create(data)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message,
                    'data': requirement
                }), 201
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 400
                
        except Exception as e:
            logger.error(f'创建需求接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/requirements/<requirement_id>', methods=['GET'])
    def get_requirement(requirement_id):
        """获取单个需求"""
        try:
            success, message, requirement = requirement_model.get_by_id(requirement_id)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message,
                    'data': requirement
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 404
                
        except Exception as e:
            logger.error(f'获取需求接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/requirements/<requirement_id>', methods=['PUT'])
    def update_requirement(requirement_id):
        """更新需求表单"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    'success': False,
                    'message': '请求数据不能为空'
                }), 400
            
            success, message, requirement = requirement_model.update(requirement_id, data)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message,
                    'data': requirement
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 400
                
        except Exception as e:
            logger.error(f'更新需求接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/requirements/<requirement_id>', methods=['DELETE'])
    def delete_requirement(requirement_id):
        """删除需求表单"""
        try:
            success, message = requirement_model.delete(requirement_id)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 404
                
        except Exception as e:
            logger.error(f'删除需求接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/requirements', methods=['GET'])
    def list_requirements():
        """获取需求列表"""
        try:
            # 获取查询参数
            page = int(request.args.get('page', 1))
            limit = int(request.args.get('limit', 10))
            status = request.args.get('status')
            
            # 参数验证
            if page < 1:
                page = 1
            if limit < 1 or limit > 100:
                limit = 10
            
            success, message, result = requirement_model.list(page, limit, status)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message,
                    'data': result
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 400
                
        except ValueError:
            return jsonify({
                'success': False,
                'message': '页码和限制数必须为有效数字'
            }), 400
        except Exception as e:
            logger.error(f'获取需求列表接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/requirements/<requirement_id>/summary', methods=['GET'])
    def get_requirement_summary(requirement_id):
        """获取需求摘要"""
        try:
            success, message, summary = requirement_model.get_summary(requirement_id)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message,
                    'data': summary
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 404
                
        except Exception as e:
            logger.error(f'获取需求摘要接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    # ==================== 方案内容相关接口 ====================
    
    @api.route('/solutions', methods=['POST'])
    def create_solution():
        """保存方案内容"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    'success': False,
                    'message': '请求数据不能为空'
                }), 400
            
            success, message, solution = solution_model.create(data)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message,
                    'data': solution
                }), 201
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 400
                
        except Exception as e:
            logger.error(f'保存方案接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/solutions/requirement/<requirement_id>/history', methods=['GET'])
    def get_solution_history(requirement_id):
        """获取方案历史记录"""
        try:
            success, message, solutions = solution_model.get_history(requirement_id)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message,
                    'data': solutions
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 404
                
        except Exception as e:
            logger.error(f'获取方案历史接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/solutions/requirement/<requirement_id>/latest', methods=['GET'])
    def get_latest_solution(requirement_id):
        """获取最新方案"""
        try:
            success, message, solution = solution_model.get_latest(requirement_id)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message,
                    'data': solution
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 404
                
        except Exception as e:
            logger.error(f'获取最新方案接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/solutions/<solution_id>/confirm', methods=['PUT'])
    def confirm_solution(solution_id):
        """确认方案"""
        try:
            success, message, solution = solution_model.confirm_solution(solution_id)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message,
                    'data': solution
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 400
                
        except Exception as e:
            logger.error(f'确认方案接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/solutions/requirement/<requirement_id>/statistics', methods=['GET'])
    def get_solution_statistics(requirement_id):
        """获取方案统计信息"""
        try:
            success, message, statistics = solution_model.get_statistics(requirement_id)
            
            if success:
                return jsonify({
                    'success': True,
                    'message': message,
                    'data': statistics
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': message
                }), 404
                
        except Exception as e:
            logger.error(f'获取方案统计接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    # ==================== 提示词相关接口 ====================
    
    @api.route('/prompts/generate', methods=['POST'])
    def generate_prompt():
        """生成AI提示词"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    'success': False,
                    'message': '请求数据不能为空'
                }), 400
            
            # 生成提示词
            prompt = PromptTemplateService.generate_prompt(data)
            
            if prompt:
                return jsonify({
                    'success': True,
                    'message': '提示词生成成功',
                    'data': {
                        'prompt': prompt,
                        'character_count': len(prompt)
                    }
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': '提示词生成失败，请检查输入数据'
                }), 400
                
        except Exception as e:
            logger.error(f'生成提示词接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/prompts/preview', methods=['POST'])
    def preview_prompt():
        """预览AI提示词"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    'success': False,
                    'message': '请求数据不能为空'
                }), 400
            
            # 预览提示词
            preview_data = PromptTemplateService.preview_prompt(data)
            
            if preview_data:
                return jsonify({
                    'success': True,
                    'message': '提示词预览成功',
                    'data': preview_data
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': '提示词预览失败，请检查输入数据'
                }), 400
                
        except Exception as e:
            logger.error(f'预览提示词接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    @api.route('/requirements/<requirement_id>/prompt', methods=['GET'])
    def get_requirement_prompt(requirement_id):
        """根据需求ID生成提示词"""
        try:
            # 获取需求数据
            success, message, requirement = requirement_model.get_by_id(requirement_id)
            
            if not success:
                return jsonify({
                    'success': False,
                    'message': message
                }), 404
            
            # 生成提示词
            prompt = PromptTemplateService.generate_prompt(requirement)
            
            if prompt:
                return jsonify({
                    'success': True,
                    'message': '提示词生成成功',
                    'data': {
                        'requirement_id': requirement_id,
                        'prompt': prompt,
                        'character_count': len(prompt),
                        'generated_at': requirement_model.get_current_timestamp().isoformat()
                    }
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': '提示词生成失败，需求数据不完整'
                }), 400
                
        except Exception as e:
            logger.error(f'根据需求生成提示词接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    # ==================== 通用接口 ====================
    
    @api.route('/health', methods=['GET'])
    def health_check():
        """健康检查接口"""
        try:
            # 检查数据库连接
            db.command('ping')
            
            return jsonify({
                'success': True,
                'message': '服务运行正常',
                'data': {
                    'status': 'healthy',
                    'database': 'connected'
                }
            }), 200
            
        except Exception as e:
            logger.error(f'健康检查失败: {str(e)}')
            return jsonify({
                'success': False,
                'message': '服务异常',
                'data': {
                    'status': 'unhealthy',
                    'error': str(e)
                }
            }), 500
    
    @api.route('/projects/<requirement_id>/export', methods=['GET'])
    def export_project(requirement_id):
        """导出项目数据"""
        try:
            # 获取需求数据
            req_success, req_message, requirement = requirement_model.get_by_id(requirement_id)
            if not req_success:
                return jsonify({
                    'success': False,
                    'message': req_message
                }), 404
            
            # 获取方案历史
            sol_success, sol_message, solutions = solution_model.get_history(requirement_id)
            if not sol_success:
                solutions = []
            
            # 获取统计信息
            stat_success, stat_message, statistics = solution_model.get_statistics(requirement_id)
            if not stat_success:
                statistics = {}
            
            export_data = {
                'requirement': requirement,
                'solutions': solutions,
                'statistics': statistics,
                'exportedAt': requirement_model.get_current_timestamp().isoformat()
            }
            
            return jsonify({
                'success': True,
                'message': '导出成功',
                'data': export_data
            }), 200
            
        except Exception as e:
            logger.error(f'导出项目接口错误: {str(e)}')
            return jsonify({
                'success': False,
                'message': f'服务器内部错误: {str(e)}'
            }), 500
    
    # ==================== 错误处理 ====================
    
    @api.errorhandler(400)
    def bad_request(error):
        """400错误处理"""
        return jsonify({
            'success': False,
            'message': '请求参数错误',
            'error': str(error)
        }), 400
    
    @api.errorhandler(404)
    def not_found(error):
        """404错误处理"""
        return jsonify({
            'success': False,
            'message': '请求的资源不存在',
            'error': str(error)
        }), 404
    
    @api.errorhandler(500)
    def internal_error(error):
        """500错误处理"""
        logger.error(f'服务器内部错误: {str(error)}')
        return jsonify({
            'success': False,
            'message': '服务器内部错误',
            'error': str(error)
        }), 500
    
    return api